package com.indra.archetypeweb.controller;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.indra.archetypeweb.entity.user.User;
import com.indra.archetypeweb.service.UserService;

@Controller
@Secured("ROLE_ADMIN")
@RequestMapping(value = "/admin")
public class AdminController {

	private static final Logger LOG = LoggerFactory
			.getLogger(AdminController.class);

	@Autowired
	private UserService userService;

	/**
	 * Inicializa usuarios dummy.
	 */
	@PostConstruct
	void initDummyData() {
		User user = new User();
		user.setUsername("admin");
		user.setPassword("admin");
		user.setEmail("admin@admin.com");
		user.setName("Administrador");
		user.setPhoneNumber("61851867");
		user.setRole("ROLE_ADMIN");
		userService.register(user);

		user = new User();
		user.setUsername("user");
		user.setPassword("user");
		user.setEmail("user@user.com");
		user.setName("Usuario");
		user.setPhoneNumber("666364485");
		userService.register(user);
	}

	@RequestMapping(method = RequestMethod.GET)
	public String index(UserDetails userDetails, Model model) {
		LOG.info(userDetails.toString());
		model.addAttribute("user", userDetails.getUsername());
		return "admin/index";
	}

	@RequestMapping(value = "/allUsers", method = RequestMethod.GET)
	public String showAllUsers(Model model) {
		List<User> users = userService.showAllUsers();
		model.addAttribute("users", users);
		return "admin/allUsers";
	}

	@RequestMapping(value = "/registerUser", method = RequestMethod.GET)
	public String registerUserForm(Model model) {
		User user = new User();
		model.addAttribute("registerUser", user);
		return "admin/registerUser";
	}

	@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
	public ModelAndView registerNewMember(
			@Valid @ModelAttribute("registerUser") User newUser,
			BindingResult result, Model model) {
		if (result.hasErrors()) {
			ModelAndView mav = new ModelAndView();
			mav.addObject("errors", result);
			return mav;
		}

		userService.register(newUser);
		return new ModelAndView("redirect:/admin/allUsers");
	}

}
